import { getKeyRouter, getLoadMapList, getTenantID } from '@/utils';
import { Button, Drawer, Form, Space, Table } from 'antd';
import React, { useEffect, useImperativeHandle, useMemo, useState } from 'react';
import { PlusCircleOutlined, MinusCircleOutlined, ClearOutlined } from '@ant-design/icons';
import pageStyles from '@/common/pageLayout.less';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import '../common/style.less';
import { SourceUpdateAPI } from '../common/type';
import { ILoadMapTypeAll } from '@/common';
import { getExtractTableConfig } from '../mconfig';
import _ from 'lodash';
import { findALLExpertsUnitService } from '../services/UpdataModalService';

export const ExtractListDrawer = React.forwardRef<SourceUpdateAPI.IExtractListFormRef, SourceUpdateAPI.ExtractListDrawerProps>(
  ({ visible, onClose, expertDataSource }, ref) => {
    /** 单位列表-屏蔽单位使用 */
    const [unitList, setUnitList] = useState<any[]>([]); // 单位列表

    /** 保存选中值 */
    const [disIDs, setDisIDs] = useState<(string | null)[]>([]);

    /** 保存选中的值 */
    const [selectKeyMap, setSelectKeyMap] = useState(new Map());

    /** 获取所有专家库中单位集合接口 */
    const { findSourceExpertsRun } = findALLExpertsUnitService((res) => {
      if (res?.msgFlag) {
        const resList: Record<string, any>[] = [];
        res?.obj?.forEach((item) => {
          if (item) {
            resList?.push({
              label: item,
              value: item,
            });
          }
        });
        setUnitList(resList);
      }
    });

    /** 初始化调用 */
    useEffect(() => {
      findSourceExpertsRun({});
    }, []);

    /** extract表单的ref */
    const [extractForm] = Form.useForm();

    useImperativeHandle(
      ref,
      () =>
        ({
          firstForm: extractForm,
          onReload: () => {
            extractForm.resetFields();
            setExtractDataSource([]);
            setDisIDs([]);
            setSelectKeyMap(new Map());
          },
        } as any),
    );

    const loadMdicIds: string[] = [`${getTenantID()}${ILoadMapTypeAll.EXPERTS_INDUSTRY_TYPE}`];
    const { loadMapInfo: loadMapInfoList, mapLoading } = getLoadMapList(loadMdicIds);

    /** 保存抽选数据 */
    const [extractDataSource, setExtractDataSource] = useState<Record<string, any>[]>(extractForm?.getFieldValue('extractTable'));

    useEffect(() => {
      extractForm?.setFieldsValue({ extractTable: extractDataSource });
    }, [extractDataSource]);

    /** 添加抽选 */
    const addMaterialCallback = () => {
      const addItemObj: Record<string, any> = {
        key: `extractTable-${getKeyRouter()}${getKeyRouter()}`,
        count: null,
        expertType: null,
      };

      setExtractDataSource((_prevState: Record<string, any>[]) => {
        const materFormValue: Record<string, any>[] = extractForm?.getFieldValue('extractTable')?.length > 0 ? extractForm?.getFieldValue('extractTable') : [];
        let newMaterial: Record<string, any>[] = [...materFormValue];
        newMaterial?.push(addItemObj);
        return newMaterial;
      });
    };

    /** 删除抽选 */
    const delMaterialCallback = (resObj: Record<string, any>, indexKey) => {
      setExtractDataSource((_prevState: Record<string, any>[]) => {
        const newDetailList: Record<string, any>[] = extractForm?.getFieldValue('extractTable')?.length > 0 ? extractForm?.getFieldValue('extractTable') : [];
        const newMaterial: Record<string, any>[] = newDetailList?.filter((item: any) => {
          if (item?.id) {
            return item?.id != resObj?.id;
          } else {
            return item?.key != resObj?.key;
          }
        });
        return newMaterial;
      });

      // 更新选中的禁用id
      // setDisIDs((_prevState) => {
      //   const newstate = _prevState?.filter((item) => item != resObj?.industryType);
      //   return newstate || [];
      // });

      selectKeyMap?.delete(resObj?.key);
      let arr: string[] = [];
      for (let val of selectKeyMap?.values()) {
        arr?.push(val);
      }
      setDisIDs(arr);
    };

    // count: null
    // expertType: null
    // key: "extractTable-f9fdec38"

    /** 下拉框选择方法 */
    const onSelectKey = (val, indexKey, recordKey) => {
      let key = recordKey?.key;
      selectKeyMap?.set(key, val);
      let arr: string[] = [];
      for (let val of selectKeyMap?.values()) {
        arr?.push(val);
      }
      setDisIDs(arr);
    };

    /** 表格行配置 */
    const columnsMemo = useMemo(() => {
      return getExtractTableConfig(delMaterialCallback, loadMapInfoList, mapLoading, unitList, disIDs, setDisIDs, selectKeyMap, onSelectKey);
    }, [loadMapInfoList, mapLoading, unitList, disIDs]);

    /** 清空 */
    const onFilter = () => {
      extractForm.resetFields();
      setExtractDataSource([]);
      setDisIDs([]);
    };

    const footer = (
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <Space>
          <Button danger onClick={onClose} icon={<MinusCircleOutlined />}>
            关闭
          </Button>
          <Button danger type="primary" icon={<ClearOutlined />} onClick={onFilter}>
            清除
          </Button>
        </Space>
      </div>
    );

    return (
      <Drawer
        open={visible}
        closable={false}
        title={<span>抽选专家</span>}
        style={{ position: 'absolute', height: '100%', overflow: 'hidden' }}
        width={document.body.clientWidth * 0.4}
        headerStyle={{ padding: '14.5px 24px' }}
        bodyStyle={{
          padding: 0,
          overflowX: 'hidden',
          overflowY: 'auto',
        }}
        placement="right"
        getContainer={document.querySelector('.ant-modal-body') as any}
        mask={false}
        onClose={onClose}
        extra={
          <Space>
            <Button type={'dashed'} size={'small'} icon={<PlusCircleOutlined />} className={'manageBtntTxtStyle'} onClick={addMaterialCallback}>
              添加
            </Button>
          </Space>
        }
        footer={footer}
      >
        <div></div>
        <ScrollBarLayout style={{ padding: '1rem' }}>
          <div className={pageStyles['fromView-styles']} style={{ padding: '5px 0' }}>
            <Form form={extractForm} style={{ marginTop: 20 }}>
              <div className={'list-table-extract-drawer'}>
                <Form.Item name="extractTable" valuePropName="dataSource">
                  <Table columns={columnsMemo} bordered size="small" dataSource={extractDataSource} rowKey={'key'} pagination={false} />
                </Form.Item>
              </div>
            </Form>
          </div>
        </ScrollBarLayout>
      </Drawer>
    );
  },
);
